package org.raymond.iworks.study.netty.demo.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

/**
 * @author raymond
 * @version V1.0
 * @Description: Handler implementation for the echo server.
 */
@ChannelHandler.Sharable
public class EchoServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        // 读取收到的数据
        ByteBuf buf = (ByteBuf)datagramPacket.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, CharsetUtil.UTF_8);
        System.out.println("收到数据:"+body);

        channelHandlerContext.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("我是server,我的时间戳是"+System.currentTimeMillis(),
                        CharsetUtil.UTF_8),
                        datagramPacket.sender())).sync();
    }
}
